

/**
 * BaiDu-OCR百度OCR
 * 
 * 1、token-调用验证码获取接口
 * 接口：https://aip.baidubce.com/oauth/2.0/token
 * 强烈建议后端访问接口获取token返回给前端
 * client_id = API Key & client_secret = secret Key
 * 获取token接口: https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=APIKey&client_secret=secretKey&
 * {"time":1573535521262,"token":"24.2a908726a2feeed67265922427b84721.2592000.1576127520.282335-16277359"}
 * 
 * 2、idcard-调用身份证识别接口
 * 接口：https://aip.baidubce.com/rest/2.0/ocr/v1/idcard
 * 返回：front-> {"data":{"log_id":4781017443523690000,"words_result_num":6,"image_status":"normal","words_result":{"住址":{"location":{"width":166,"top":314,"left":65,"height":40},"words":"新疆哈密市北郊路86院30栋3单元201号"},"出生":{"location":{"width":0,"top":0,"left":0,"height":0},"words":"19750828"},"姓名":{"location":{"width":49,"top":247,"left":72,"height":13},"words":"雷青春"},"公民身份号码":{"location":{"width":215,"top":374,"left":133,"height":35},"words":"652201197508281619"},"性别":{"location":{"width":11,"top":272,"left":70,"height":11},"words":"男"},"民族":{"location":{"width":10,"top":269,"left":143,"height":9},"words":"汉"}}},"statusCode":200,"header":{"Access-Control-Allow-Origin":"*","Appid":"16277359","Connection":"keep-alive","Content-Type":"application/json","Date":"Tue, 12 Nov 2019 13:28:18 GMT","P3p":"[CP=\" OTI DSP COR IVA OUR IND COM \", CP=\" OTI DSP COR IVA OUR IND COM \", CP=\" OTI DSP COR IVA OUR IND COM \"]","Server":"Apache","Set-Cookie":"[BAIDUID=B369C2A2D020CB5E970B5F85BCE68B6F:FG=1; expires=Wed, 11-Nov-20 13:28:19 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1, BAIDUID=A016836F28FE093F5FEBC15A98A16C6D:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2145916555; path=/; domain=.baidu.com; version=1, BAIDUID=A016836F28FE093F2DD6E606A7F82238:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2145916555; path=/; domain=.baidu.com; version=1]","Tracecode":"16990350280316447498111221","Vary":"Accept-Encoding","X-Android-Received-Millis":"1573565297547","X-Android-Response-Source":"NETWORK 200","X-Android-Selected-Protocol":"http/1.1","X-Android-Sent-Millis":"1573565296530","_":"HTTP/1.1 200 OK"},"errMsg":"request:ok"}
 * 返回：back-> {"data":{"log_id":2567622507036354000,"words_result_num":3,"image_status":"normal","words_result":{"失效日期":{"location":{"width":60,"top":406,"left":247,"height":17},"words":"20280704"},"签发机关":{"location":{"width":75,"top":384,"left":172,"height":19},"words":"哈密市公安局"},"签发日期":{"location":{"width":67,"top":413,"left":174,"height":18},"words":"20080704"}}},"statusCode":200,"header":{"Access-Control-Allow-Origin":"*","Appid":"16277359","Connection":"keep-alive","Content-Type":"application/json","Date":"Tue, 12 Nov 2019 13:28:45 GMT","P3p":"[CP=\" OTI DSP COR IVA OUR IND COM \", CP=\" OTI DSP COR IVA OUR IND COM \", CP=\" OTI DSP COR IVA OUR IND COM \"]","Server":"Apache","Set-Cookie":"[BAIDUID=E68F1D22465F1B5FECB7A098D87376C8:FG=1; expires=Wed, 11-Nov-20 13:28:45 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1, BAIDUID=62C4FF7DE4FB03BA75F25A6247A8A00D:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2145916555; path=/; domain=.baidu.com; version=1, BAIDUID=44C15E1C02531426EB076E6552B4D405:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2145916555; path=/; domain=.baidu.com; version=1]","Tracecode":"17256462700548313354111221","Vary":"Accept-Encoding","X-Android-Received-Millis":"1573565324078","X-Android-Response-Source":"NETWORK 200","X-Android-Selected-Protocol":"http/1.1","X-Android-Sent-Millis":"1573565323220","_":"HTTP/1.1 200 OK"},"errMsg":"request:ok"}
 * 
 * 3、bankcard-调用银行卡识别接口
 * 接口：https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard'
 * 返回：data":{"result":{"bank_card_type":2,"bank_name":"建设银行","bank_card_number":"6259 6508 7663 0655","valid_date":"05/21"}
 * 
 * 4、detect-上传人脸图片到服务端进行人脸检测
 * 接口：https://aip.baidubce.com/rest/2.0/face/v3/detect
 * 返回：data:{"error_code":0,"error_msg":"SUCCESS","log_id":1011010584350,"timestamp":1573563748,"cached":0,"result":{"face_num":1,"face_list":[{"face_token":"1c80a3dfdef0b12badf87c014a046071","location":{"left":98.23,"top":196.42,"width":190,"height":215,"rotation":0},"face_probability":1,"angle":{"yaw":7.45,"pitch":-7.17,"roll":-1.68},"quality":{"occlusion":{"left_eye":0.06,"right_eye":0,"nose":0,"mouth":0,"left_cheek":0,"right_cheek":0.04,"chin_contour":0},"blur":0.03,"illumination":132,"completeness":1}}]}},"statusCode":200,
 * 判断依据：result.result.face_num>0&&result.result.face_list[0].quality.completeness==1
 * 
 * 5、faceverify-上传人脸图片到服务端在线活体检测
 * 接口：https://aip.baidubce.com/rest/2.0/face/v3/faceverify
 * 返回：{"data":{"error_code":0,"error_msg":"SUCCESS","log_id":5575056589990,"timestamp":1573565365,"cached":0,"result":{"thresholds":{"frr_1e-4":0.05,"frr_1e-3":0.3,"frr_1e-2":0.9},"face_liveness":1,"face_list":[{"face_token":"c61749d11e395d4fd187a10871fe1396","location":{"left":85.21,"top":266.82,"width":198,"height":231,"rotation":3},"face_probability":1,"angle":{"yaw":-0.4,"pitch":-13.06,"roll":1.94},"liveness":{"livemapscore":1}}]}},"statusCode":200,"header":{"Access-Control-Allow-Headers":"X-Requested-With","Access-Control-Allow-Methods":"GET,POST,OPTIONS","Access-Control-Allow-Origin":"*","Appid":"16277359","Connection":"keep-alive","Content-Type":"application/json","Date":"Tue, 12 Nov 2019 13:29:25 GMT","P3p":"[CP=\" OTI DSP COR IVA OUR IND COM \", CP=\" OTI DSP COR IVA OUR IND COM \"]","Server":"Apache","Set-Cookie":"[BAIDUID=4AAC1A214032A79F3C803028FFA46581:FG=1; expires=Wed, 11-Nov-20 13:29:25 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1, BAIDUID=33C4542E4CF1F765DE0A547A9ED87AAC:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2145916555; path=/; domain=.baidu.com; version=1]","Tracecode":"17653667060531588874111221","Vary":"Accept-Encoding","X-Android-Received-Millis":"1573565363877","X-Android-Response-Source":"NETWORK 200","X-Android-Selected-Protocol":"http/1.1","X-Android-Sent-Millis":"1573565363399","_":"HTTP/1.1 200 OK"},"errMsg":"request:ok"}
 * 判断依据：face_liveness>0.995
 * 
 * 6、match-上传人脸图片和证件不偏到服务端进行人脸比对
 * 接口：https://aip.baidubce.com/rest/2.0/face/v3/match
 * 返回：{"data":{"error_code":0,"error_msg":"SUCCESS","log_id":5525897984350,"timestamp":1573565367,"cached":0,"result":{"score":93.36450195,"face_list":[{"face_token":"c61749d11e395d4fd187a10871fe1396"},{"face_token":"ec1b264f8de771fe7e64e43ec17c113a"}]}},"statusCode":200,"header":{"Access-Control-Allow-Headers":"X-Requested-With","Access-Control-Allow-Methods":"GET,POST,OPTIONS","Access-Control-Allow-Origin":"*","Appid":"16277359","Connection":"keep-alive","Content-Type":"application/json","Date":"Tue, 12 Nov 2019 13:29:27 GMT","P3p":"[CP=\" OTI DSP COR IVA OUR IND COM \", CP=\" OTI DSP COR IVA OUR IND COM \"]","Server":"Apache","Set-Cookie":"[BAIDUID=D7FD976F9B86EABFB370D247645F1FCD:FG=1; expires=Wed, 11-Nov-20 13:29:27 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1, BAIDUID=9C186BDA4C1516E2492A024BE003F8C7:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2145916555; path=/; domain=.baidu.com; version=1]","Tracecode":"17671086470531588874111221","Vary":"Accept-Encoding","X-Android-Received-Millis":"1573565365845","X-Android-Response-Source":"NETWORK 200","X-Android-Selected-Protocol":"http/1.1","X-Android-Sent-Millis":"1573565365093","_":"HTTP/1.1 200 OK"},"errMsg":"request:ok"}
 * 判断依据：result.result.score>=80
 **/
 
const getOCRUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1';
const getFaceUrl= 'https://aip.baidubce.com/rest/2.0/face/v3'

function token() {
	return new Promise((rs, rj) => {
		console.log('准备访问接口获取OCR识别token')
		try {
		    var res = uni.getStorageSync('BDOCRToken');
		    if (res) {
		        console.log(res);
				var startTime=res.time;
				var token=res.token;
				var endTime=new Date().getTime();
				var diff=(endTime - startTime) / (1000 * 60 * 60 * 24)//一天的时间数
				if(diff<30) return rs(token);
		    }
		} catch (e) {// error
		    console.log(e);
		}
		uni.request({ // 强烈建议此接口由后端访问并且维护token有效期，否则前端每次访问都会刷新token
			//此url为专门插件测试预览用的key和secret key， 请替换为自己申请的key
			url: 'https://aip.baidubce.com/oauth/2.0/token',
			method: 'POST', 
			data: {
				grant_type:'client_credentials',
				client_id:'DQBFCEO9ivTqwqxgsIFD2WxR',
				client_secret:'jGQY6nh76KVAdMDSOCU5NXrPUce8dmSV'
			},
			header: {
				"content-type": "application/x-www-form-urlencoded"
			},
			success: (res) => {
				console.log('访问成功:', res);
				if(res&&res.data&&res.data.access_token) {
					uni.setStorageSync('BDOCRToken', {time:new Date().getTime(),token:res.data.access_token});
					rs(res.data.access_token);
				}
				else{
					console.log(res.data.error_description);
					rs('');
					rj(false)
				}
			},
			fail: (err) => {
				console.log('访问失败');
				rs('');
				rj(false);
			}
		});
	})
}
//上传身份证图片到服务端获取证件信息
//'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard';
//front-> "data":{"性别":"男","姓名":"雷青春","住址":"新疆哈密市北郊路86院30栋3单元201号","公民身份号码":"652201197508281619","出生":"19750828","民族":"汉"}
//back-> "data":{"失效日期":"20280704","签发机关":"哈密市公安局","签发日期":"20080704"}
function idcard(obj,succ,fail){
	uni.request({ 
		url: getOCRUrl+'/idcard',
		method: 'POST', 
		data:{ 
			image:obj.b64, 
			id_card_side: obj.side,//front-正面|back-背面
			access_token: obj.token
		},
		header: {
			"content-type": "application/x-www-form-urlencoded"
		},
		success: (res) => {
			console.log('访问成功:',res);
			 if(res.statusCode==200) {
				var result={}
				if(res.data&&res.data.words_result) {
					for(var key in res.data.words_result) {
						result[key]=res.data.words_result[key].words
					}
					 console.log('result:',result)
					 return succ(result)
				}
			 }
			 uni.showToast({icon:'none',title:'证件识别OCR返回数据有误！'})
			 fail(false)
		},
		fail: (err) => {
			console.log('访问失败:',err);
			uni.showToast({icon:'none',title:'证件识别OCR调用失败！'})
			fail(false);
		}
	});
}
//上传银行卡图片到服务端获取证件信息
//'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard'
//"data":{"result":{"bank_card_type":2,"bank_name":"建设银行","bank_card_number":"6259 6508 7663 0655","valid_date":"05/21"}
function bankcard(obj,succ,fail){
	uni.request({ 
		url: getOCRUrl+'/bankcard',
		method: 'POST', 
		data:{ 
			image:obj.b64, 
			access_token: obj.token
		},
		header: {
			"content-type": "application/x-www-form-urlencoded"
		},
		success: (res) => {
			console.log('访问成功:',res);
			 if(res.statusCode==200) {
				var result={}
				if(res.data) {
					result=res.data
					return succ(result)
				}
			 }
			 uni.showToast({icon:'none',title:'证件识别OCR返回数据有误！'})
			 fail(false)
		},
		fail: (err) => {
			console.log('访问失败:',err);
			uni.showToast({icon:'none',title:'证件识别OCR调用失败！'})
			fail(false);
		}
	});
}

//上传人脸图片到服务端进行人脸检测
//"data":{"error_code":0,"error_msg":"SUCCESS","log_id":1011010584350,"timestamp":1573563748,"cached":0,"result":{"face_num":1,"face_list":[{"face_token":"1c80a3dfdef0b12badf87c014a046071","location":{"left":98.23,"top":196.42,"width":190,"height":215,"rotation":0},"face_probability":1,"angle":{"yaw":7.45,"pitch":-7.17,"roll":-1.68},"quality":{"occlusion":{"left_eye":0.06,"right_eye":0,"nose":0,"mouth":0,"left_cheek":0,"right_cheek":0.04,"chin_contour":0},"blur":0.03,"illumination":132,"completeness":1}}]}},"statusCode":200,
//判断依据：result.result.face_num>0&&result.result.face_list[0].quality.completeness==1
function detect(obj,succ,fail){
	uni.request({ 
		url: getFaceUrl+'/detect?access_token='+obj.token,
		method: 'POST', 
		data:{ 
			image:obj.b64, 
			image_type:obj.image_type||"BASE64",
			max_face_num:obj.max_face_num||1,
			face_field:obj.face_field||"quality",
		},
		header: {
			"content-type": "application/json"
		},
		success: (res) => {
			console.log('访问成功:',res);
			 if(res.statusCode==200) {
				var result={}
				if(res.data) {
					result=res.data
					return succ(result)
				}
			 }
			 uni.showToast({icon:'none',title:'人脸检测返回数据有误！'})
			 fail(false)
		},
		fail: (err) => {
			console.log('访问失败:',err);
			uni.showToast({icon:'none',title:'人脸检测调用失败！'})
			fail(false);
		}
	});
}
//上传人脸图片到服务端进行活体检测
//'https://aip.baidubce.com/rest/2.0/face/v3/faceverify'
//{"error_code":0,"error_msg":"SUCCESS","log_id":2565797965947,"timestamp":1573563559,"cached":0,"result":{"thresholds":{"frr_1e-4":0.05,"frr_1e-3":0.3,"frr_1e-2":0.9},"face_liveness":0.91,"face_list":[{"face_token":"e79e0dc48f7239fcf6a064fd02023bbb","location":{"left":255.38,"top":293.29,"width":64,"height":60,"rotation":-6},"face_probability":1,"angle":{"yaw":3.17,"pitch":4.99,"roll":-10.41},"liveness":{"livemapscore":0.91}}]}}
//判断依据：face_liveness>0.995
function faceverify(obj,succ,fail){
	uni.request({ 
		url: getFaceUrl+'/faceverify?access_token='+obj.token,
		method: 'POST', 
		data:[
			{
				image:obj.image,
				image_type:obj.image.length<50?"FACE_TOKEN":"BASE64",
			}
		],
		header: {
			"content-type": "application/json"
		},
		success: (res) => {
			console.log('访问成功:',res);
			 if(res.statusCode==200) {
				var result={}
				if(res.data) {
					result=res.data
					return succ(result)
				}
			 }
			 uni.showToast({icon:'none',title:'活体检测返回数据有误！'})
			 fail(false)
		},
		fail: (err) => {
			console.log('访问失败:',err);
			uni.showToast({icon:'none',title:'活体检测调用失败！'})
			fail(false);
		}
	});
}
//上传人脸图片到服务端进行人脸比对
//'https://aip.baidubce.com/rest/2.0/face/v3/match'
//{"timestamp":1559192037,"result":{"face_list":[{"face_token":"d57a2bc56b80103d14c6d92eff606848"},{"face_token":"01a5ddc91704366fea3649577f3f113b"}],"score":31.06158638},"cached":0,"error_code":0,"log_id":304592891920377521,"error_msg":"SUCCESS"}
//判断依据：result.result.score>=80
function match(obj,succ,fail){
	uni.request({ 
		url: getFaceUrl+'/match?access_token='+obj.token,
		method: 'POST', 
		data:[
			{
				image:obj.Live_Image,
				image_type:obj.Live_Image.length<50?"FACE_TOKEN":"BASE64",
				face_type:"LIVE",
			},
			{
				image:obj.IDCard_Image,
				image_type:obj.IDCard_Image.length<50?"FACE_TOKEN":"BASE64",
				face_type:"CERT",
			},
		],
		header: {
			"content-type": "application/json"
		},
		success: (res) => {
			console.log('访问成功:',res);
			 if(res.statusCode==200) {
				var result={}
				if(res.data) {
					result=res.data
					return succ(result)
				}
			 }
			 uni.showToast({icon:'none',title:'人脸比对返回数据有误！'})
			 fail(false)
		},
		fail: (err) => {
			console.log('访问失败:',err);
			uni.showToast({icon:'none',title:'人脸比对调用失败！'})
			fail(false);
		}
	});
}

function ocr(obj){
	console.log('ocr.func:',obj.func)
	return new Promise(async (rs, rj) => {
		if(!obj.token) obj.token=await token()
		if(obj.func) return this[obj.func](obj,rs,rj);
	});
};

/*
 use exam:
 import OCR from '@/common/js/js_sdk/BaiDu-OCR/BaiDu-OCR.js';
 var ocr = await OCR.ocr(obj);
*/
export default {
	ocr: ocr,
	token: token,
	idcard: idcard,
	bankcard: bankcard,
	detect: detect,
	faceverify: faceverify,
	match: match,
};